package com.forever7776.life.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.forever7776.life.core.common.enums.EmailTemplateTypeEnum;
import com.forever7776.life.core.common.enums.SysUserEnum;
import com.forever7776.life.core.common.enums.UserBlogTypeEnum;
import com.forever7776.life.core.common.util.ResultVoUtil;
import com.forever7776.life.core.common.vo.*;
import com.forever7776.life.core.entity.comment.CommentTweet;
import com.forever7776.life.core.entity.sys.SysUser;
import com.forever7776.life.core.service.ITweetsService;
import com.forever7776.life.core.service.blog.IBlogService;
import com.forever7776.life.core.service.comment.ICommentTweetService;
import com.forever7776.life.core.service.sys.ISysUserService;
import com.forever7776.life.remote.common.consants.PlaceHoldersConstants;
import com.forever7776.life.remote.common.vo.ResultVO;
import com.forever7776.life.remote.rpc.SendEmailRpcService;
import com.forever7776.sendcloud.remote.common.vo.SendCloudEmailParamVO;
import enums.ResultEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import util.ResultUtil;
import util.ValidateUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户类
 * </p>
 *
 * @author kz
 * @date 2018-03-15
 */
@Controller
@RequestMapping("/u")
public class UserController extends BaseController {

    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private IBlogService iBlogService;
    @Autowired
    private SendEmailRpcService sendEmailRpcService;
    @Autowired
    private ICommentTweetService iCommentTweetService;
    @Autowired
    private ITweetsService iTweetsService;


    /**
     * 查看用户资料
     *
     * @param username
     */
    @RequestMapping("/{username}")
    public String index(@PathVariable String username, ModelMap map) {
        SysUser sysUser = iSysUserService.selectByUserName(username);
        map.put("m", sysUser);
        UserBlogSearchVO vo = new UserBlogSearchVO();
        vo.setUserId(sysUser.getId());
        map.put("blogs", iBlogService.selectAll(new Page<>(pageNumber, pageSize), vo));
        map.put("SEX_MAP", SysUserEnum.SEX_MAP);
        return FRONT_VIEW_PAGE_PATH_LIFES + "front/user_info";
    }

    /**
     * 查询用户发布的博客
     *
     * @return
     */
    @RequestMapping("/blogs/{userId}")
    @ResponseBody
    public JSONObject blogs(@PathVariable String userId) {
        JSONObject result = new JSONObject();
        Page<UserBlogVO> p = new Page<UserBlogVO>();
        p.setCurrent(pageNumber);
        Page<UserBlogVO> page = iBlogService.selectAllUserBlogByFront(p, UserBlogTypeEnum.TYPE.READ.getCode(), null, userId);
        result.put("page", page);
        return result;
    }

    /**
     * 查询用户发布的动弹以及评论
     *
     * @return
     */
    @RequestMapping("/tweets/{userId}")
    @ResponseBody
    public JSONObject tweets(@PathVariable String userId) {
        JSONObject result = new JSONObject();
        Page<UserTweetsVO> p = new Page<>();
        p.setCurrent(pageNumber);
        //查询动弹列表
        String currentUserId = "";
        if (getSysUser() != null) {
            currentUserId = getUserId();
        }
        Page<UserTweetsVO> page = iTweetsService.selectUserTweets(p, userId,currentUserId);
        List<UserTweetsVO> tweetsVOList = page.getRecords();
        //查询评论列表
        List<UserCommentVO> commentVOList = iCommentTweetService.selectUserCommentsList(userId,null);
        page.setRecords(createComments(tweetsVOList, commentVOList));
        List<String> userIds = iCommentTweetService.selectUserIds(userId);
        List<UserBaseInfoVO> users = iSysUserService.selectUserBaseInfos(userIds);
        result.put("page", page);
        result.put("usersMap", createUserMap(users));
        return result;
    }

    /**
     * 用户资料页面，动弹列表，添加评论
     *
     * @param tweetId
     * @param content
     * @param replyUserId
     * @return
     */
    @RequestMapping(value = "/add/comment/{tweetId}", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject addComment(@PathVariable Integer tweetId,
                                @RequestParam("content") String content,
                                @RequestParam(value = "replyUserId", required = false) String replyUserId) {
        if (tweetId == null || tweetId < 1) {
            return ResultUtil.getFailResult("该动弹不存在~");
        }
        if (StringUtils.isEmpty(content) || content.length() > 255) {
            return ResultUtil.getFailResult("内容不规范~");
        }
        String userId = iTweetsService.selectUserIdById(tweetId);
        if (userId.equals(getUserId()) && StringUtils.isNotEmpty(replyUserId) && replyUserId.equals(getUserId())) {
            return ResultUtil.getFailResult("自己不能回复自己~");
        }
        CommentTweet comment = new CommentTweet();
        comment.setUserId(getUserId());
        comment.setReplyUserId(replyUserId);
        comment.setContent(content);
        comment.setTweetId(tweetId);
        iCommentTweetService.insert(comment);
        return ResultUtil.getSuccessResult("");
    }

    /**
     * 通过邮箱找回密码
     *
     * @param email
     * @return
     */
    @RequestMapping(value = "/forget/pwd", method = RequestMethod.POST)
    @ResponseBody
    public ResultVO findPasswordByEmail(@RequestParam("email") String email,
                                        @RequestParam("username") String username) {
        String realEmail = JSONObject.parseArray(email).get(0).toString();
        ResultVO result = checkFormFindPasswordByEmail(realEmail, username);
        if (!result.getCode().equals(ResultEnum.STATUS.SUCCESS.getCode())) {
            return result;
        }
        SysUser sysUser = iSysUserService.selectOneByUsernameAndEmail(username, realEmail);
        if (sysUser == null) {
            return ResultVoUtil.getFailResult("不存在该用户");
        }
        SendCloudEmailParamVO vo = sendEmailRpcService.createSendEmailVo(null, email, EmailTemplateTypeEnum.TYPE.RETRIEVE_PASSWORD.getKey());
        Map<String, String> map = new HashMap<>(1);
        map.put(PlaceHoldersConstants.USER_NAME, sysUser.getUsername());
        map.put(PlaceHoldersConstants.PASSWORD, sysUser.getPassword());
        vo.setPlaceholders(map);
        com.forever7776.sendcloud.remote.common.vo.ResultVO resultVO = sendEmailRpcService.sendEmail(vo);
        if (resultVO.getCode().equals(200)) {
            logger.info("用户【{}】找回密码，发送邮件成功，{}", sysUser.getUsername(), email);
        } else {
            logger.info("发送邮件失败，原因：{}", resultVO.getMsg());
        }
        return result;
    }

    /**
     * 检查是否用户登录
     *
     * @return
     */
    @RequestMapping("/logined")
    @ResponseBody
    public JSONObject checkLogined() {
        JSONObject result = ResultUtil.getSuccessResult("已登录");
        SysUser user = getSysUser();
        if (user == null) {
            result = ResultUtil.getFailResult("没有登录");
            return result;
        }
        result.put("user", user);
        return result;
    }


    public ResultVO checkFormFindPasswordByEmail(String email, String username) {
        ResultVO result = new ResultVO();
        if (StringUtils.isEmpty(username)) {
            result.setCode(ResultEnum.STATUS.FAIL.getCode());
            result.setMsg("登录名称为空~~~");
            return result;
        }
        if (StringUtils.isEmpty(email)) {
            result.setCode(ResultEnum.STATUS.FAIL.getCode());
            result.setMsg("邮箱为空~~~");
            return result;
        }
        if (!ValidateUtil.verifyEmailIsPassed(email)) {
            result.setCode(ResultEnum.STATUS.FAIL.getCode());
            result.setMsg("请输入正确的邮箱~~~");
            return result;
        }
        result.setCode(ResultEnum.STATUS.SUCCESS.getCode());
        result.setMsg("发送邮件成功！");
        return result;
    }


    /**
     * 构造评论map
     *
     * @param tweetsVOList
     * @param commentVOList
     * @return
     */
    public List<UserTweetsVO> createComments(List<UserTweetsVO> tweetsVOList, List<UserCommentVO> commentVOList) {
        if (CollectionUtils.isEmpty(commentVOList)) {
            return tweetsVOList;
        }

        for (UserTweetsVO vo : tweetsVOList) {
            Integer tweetId = vo.getTweetId();
            List<UserCommentVO> list = new ArrayList<>();
            for (UserCommentVO commentVO : commentVOList) {
                if (tweetId.equals(commentVO.getTweetId())) {
                    list.add(commentVO);
                }
            }
            vo.setComments(list);
        }
        return tweetsVOList;
    }


}
